package work;

import java.io.IOException;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.File;

public class WorkUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings({ "unchecked" })
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
		if (isMultipart)
		{  
			// Create a new file upload handler
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
		
			//Parse the request
			List items;
			try {
				items = upload.parseRequest(request);
				// Process the uploaded items
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
				    FileItem item = (FileItem) iter.next();

				    if (item.isFormField()) {
				       //TODO work with no file field
				    } else {

			    	    String fileName = item.getName();
			    	    // Write to a file at a path
		    	        File uploadedFile = new File("/home/lucas/eclipse/mc436/root/workFolder/"+fileName);
		    	        item.write(uploadedFile);
				    }
				}
				// Forward to a page
    	        RequestDispatcher rdIndex = request.getRequestDispatcher("upload.jsp");
    			rdIndex.forward(request, response);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	       }
	
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
	{
		// same logic
		this.doGet(request, response);
	}
}
